<template>
  <div>
    <el-card style="height: 80px">
      <el-form :inline="true" class="form">
        <el-form-item label="用户名">
          <el-input
            placeholder="请输入用户名"
            v-model="searchParams"
          ></el-input>
        </el-form-item>
        <el-form-item style="margin: 0">
          <el-button
            type="primary"
            :disabled="!searchParams"
            @click="searchUser"
            >搜索</el-button
          >
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin: 10px 0">
      <el-button type="primary" @click="addUser">添加用户</el-button>
      <el-button
        type="primary"
        :disabled="!selectIdArr.length"
        @click="deleteAllUser"
        >批量删除</el-button
      >
      <!-- 表格:展示用户信息 -->
      <el-table
        @selection-change="selectionChange"
        style="margin: 10px 0"
        border
        :data="userArr"
      >
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column
          label="#"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column label="ID" align="center" prop="id"></el-table-column>
        <el-table-column
          label="用户名"
          align="center"
          prop="username"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="用户名称"
          align="center"
          prop="name"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="用户角色"
          align="center"
          prop="roleName"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="更新时间"
          align="center"
          prop="updateTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" width="300px" align="center">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="User"
              @click="setRole(row)"
              >分配角色</el-button
            >
            <el-button
              type="warning"
              size="small"
              icon="Edit"
              @click="updateUser(row)"
              >编辑</el-button
            >
            <el-popconfirm
              :title="`你确定删除${row.name}吗?`"
              @confirm="deleteUser(row)"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="Delete"
                  >删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 7, 9, 11]"
        :background="true"
        layout=" prev, pager, next, jumper,->,sizes,total "
        :total="total"
        @change="getUserInfo(pageNo)"
      />
    </el-card>
    <!-- 抽屉效果 用于添加用户信息 -->
    <el-drawer v-model="drawer">
      <template #header>
        <h4>{{ userParams.id ? "更新用户" : "添加用户" }}</h4>
      </template>
      <template #default>
        <el-form :model="userParams" :rules="rules" ref="formRef">
          <el-form-item label="用户名" prop="username">
            <el-input
              placeholder="请输入用户名"
              v-model="userParams.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户名称" prop="name">
            <el-input
              placeholder="请输入用户名称"
              v-model="userParams.name"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="!userParams.id" label="用户密码" prop="password">
            <el-input
              placeholder="请输入用户密码"
              v-model="userParams.password"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 抽屉效果 用于分配角色 -->
    <el-drawer v-model="drawer1">
      <template #header>
        <h4>分配角色</h4>
      </template>
      <template #default>
        <el-form>
          <el-form-item label="用户姓名">
            <el-input v-model="userParams.name" disabled="true"></el-input>
          </el-form-item>
          <el-form-item laebl="职位列表">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="indeterminate"
              @change="handleCheckAllChange"
              >全选
            </el-checkbox>
            <!-- 显示职位的复选框 -->
            <el-checkbox-group
              v-model="userRole"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="(role, index) in allRole"
                :key="index"
                :label="role.roleName"
                :value="role"
              >
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer1 = false">取消</el-button>
          <el-button type="primary" @click="confirmRole">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import {
  reqUserInfo,
  reqAddOrUpdateUser,
  reqAllRole,
  reqAssignRole,
  reqDeleteUser,
  reqAllDeleteUser,
} from "@/api/acl/user";
import { ElMessage } from "element-plus";
const pageNo = ref(1);
const pageSize = ref(9);
const total = ref(0);

// 存储用户数据
const userArr = ref([]);
// 控制抽屉的显示隐藏
const drawer = ref(false);
const drawer1 = ref(false);

// 收集用户信息的响应式数据
const userParams = ref<any>({});

// 获取form组件实例
const formRef = ref();

// 准备一个数组存储批量删除的Id
const selectIdArr = ref<number[]>([]);

// 收集用户搜索时输入的信息
const searchParams = ref<string>("");

// 封装渲染函数
const getUserInfo = async (pager = 1) => {
  pageNo.value = pager;
  const res = await reqUserInfo(
    pageNo.value,
    pageSize.value,
    searchParams.value
  );
  if (res.code === 200) {
    userArr.value = res.data.records;
    total.value = res.data.total;
  }
};

// 添加用户按钮回调
const addUser = () => {
  // 清空表单数据
  userParams.value = {};
  drawer.value = true;
  // 清空表单验证
  nextTick(() => {
    formRef.value.clearValidate();
  });
};

// 编辑已有用户信息按钮回调
const updateUser = (row: any) => {
  // 清空表单验证
  nextTick(() => {
    formRef.value.clearValidate();
  });
  // 收集已有的表单信息
  Object.assign(userParams.value, row);
  drawer.value = true;
};

// 点击确定按钮回调
const save = async () => {
  // 表单验证是否通过
  await formRef.value.validate();

  // 有id:编辑 无id:添加
  const res = await reqAddOrUpdateUser(userParams.value);
  // 添加或更新成功
  if (res.code === 200) {
    drawer.value = false;
    // 浏览器自动刷新一次
    // window.location.reload();
    // 提示消息
    ElMessage.success(userParams.value.id ? "更新成功" : "添加成功");
    // 重新渲染数据
    getUserInfo(userParams.value.id ? pageNo.value : 1);
  } else {
    drawer.value = false;
    // 添加或更新失败
    ElMessage.error(userParams.value.id ? "更新失败" : "添加失败");
  }
};

// 取消按钮的回调
const cancel = () => {
  drawer.value = false;
};

const validatorUserName = (rule: any, value: any, callback: any) => {
  if (!value || value.trim().length < 5) {
    // 先判断 value 是否存在
    callback(new Error("用户名长度不能小于5位"));
  } else {
    callback();
  }
};

const validatorName = (rule: any, value: any, callback: any) => {
  if (!value || value.trim().length < 3) {
    // 先判断 value 是否存在
    callback(new Error("用户姓名长度不能小于3位"));
  } else {
    callback();
  }
};

// 表单校验的规则对象
const rules = {
  // 用户名字
  username: [{ required: true, trigger: "blur", validator: validatorUserName }],
  name: [{ required: true, trigger: "blur", validator: validatorName }],
  password: [
    {
      required: !userParams.value.id,
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        if (userParams.value.id) {
          // 编辑模式跳过校验
          callback();
          return;
        }
        if (!value || value.length < 6) {
          // 处理空值
          callback(new Error("密码长度不能少于6位"));
        } else {
          callback();
        }
      },
    },
  ],
};

// 分配角色按钮的回调
const setRole = async (row: any) => {
  // 存储已有的用户信息
  Object.assign(userParams.value, row);
  // 发送请求获取全部职位
  const res = await reqAllRole(row.id);
  if (res.code === 200) {
    // 存储全部职位
    allRole.value = res.data.allRolesList;
    // 存储用户已有的职位
    userRole.value = res.data.assignRoles;
    // 显示抽屉
    drawer1.value = true;
  }
};

// 复选框判断是否全选
const checkAll = ref(false);
// 复选框设置不确定样式
const indeterminate = ref(true);
// 显示职位的复选框
const allRole = ref<any>([]);
const userRole = ref<any>([]);
// 全选复选框的change事件
const handleCheckAllChange = (val: boolean) => {
  userRole.value = val ? allRole.value : [];
  indeterminate.value = false;
};

// 职位复选框的change事件
const handleCheckedCitiesChange = (value: any) => {
  // 判断是否全选
  const checkedCount = value.length;
  // 代表选中的职位数量等于所有职位数量
  checkAll.value = checkedCount === allRole.value.length;
  // 已经勾选但并未全选 即为不确定状态
  indeterminate.value = checkedCount > 0 && checkedCount < allRole.value.length;
};

// 确定按钮的回调(分配职位)
const confirmRole = async () => {
  // 收集数据
  const data: any = {
    userId: userParams.value.id,
    roleIdList: userRole.value.map((item: any) => item.id),
  };
  console.log(data);

  // 调用接口
  const res = await reqAssignRole(data);
  if (res.code === 200) {
    ElMessage.success("分配职位成功");
    // 关闭弹窗
    drawer1.value = false;
    // 重新渲染数据
    getUserInfo(pageNo.value);
  } else {
    ElMessage.error("分配职位失败");
  }
};

// 删除某一个用户
const deleteUser = async (row: any) => {
  const id = Number(row.id);
  const res = await reqDeleteUser(id);
  if (res.code === 200) {
    ElMessage.success("删除用户成功");
    // 删除成功后重新渲染数据
    getUserInfo(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
  } else {
    ElMessage.error("删除用户失败");
  }
};

// table复选框 勾选的时候触发的事件
const selectionChange = (value: any) => {
  selectIdArr.value = value;
};

// 批量删除按钮的回调
const deleteAllUser = async () => {
  const idList = selectIdArr.value.map((item: any) => item.id);

  const res = await reqAllDeleteUser(idList);
  if (res.code === 200) {
    ElMessage.success("删除用户成功");
    getUserInfo(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
  } else {
    ElMessage.error("删除用户失败");
  }
};

// 搜索按钮回调
const searchUser = async () => {
  // 根据关键字获取用户信息
  getUserInfo();
  // 清空用户输入
  searchParams.value = "";
};

// 重置按钮回调
const reset = () => {
  searchParams.value = "";
  getUserInfo();
};

// 页面挂载时渲染数据
onMounted(() => {
  getUserInfo();
});
</script>

<style scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
